//
//  DLLoadingRunTip.m
//  DGGMobileFrameworksDemo
//
//  Created by 伍明鹏 on 2019/12/24.
//  Copyright © 2019 伍明鹏. All rights reserved.
//

#import "DLLoadingRunTip.h"
#import <Masonry/Masonry.h>
#import "UIView+Extension.h"
#define MARGIN 35
#define DEFAULT_ANIMATION_TIME 0.2

@interface DLLoadingRunTip()
//旋转动画
@property (nonatomic, strong) CABasicAnimation *rotationAnimation;
//自定义layer
@property (nonatomic, strong) CALayer *refreshLayer;
//内容视图
@property (nonatomic, strong) UIView *contentView;
//显示文字“加载中”
@property (nonatomic, strong) UILabel *lab;

@property (nonatomic, assign) BOOL isAllShow;

//放置圆圈和文字的容器
@property (nonatomic, strong) UIView *containerView;

@end
@implementation DLLoadingRunTip

- (instancetype)init{
    if (self = [super init]) {
        [self config];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self config];
    }
    return self;
}

//局部
- (void)showLoadingMessage:(NSString *)message
                 superView:(UIView *)superVie
                    radius:(CGFloat)radius{
    self.message = message;
    self.radius = radius;
    self.isAllShow = NO;
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [superVie addSubview:self];
    [superVie bringSubviewToFront:self];
    [self removeSubviews];
    self.frame = superVie.bounds;
    
    [self show];
}
//全局
- (void)showBigLoadingMessage:(NSString *)message
                    superView:(UIView *)superVie
                       radius:(CGFloat)radius{
    self.message = message;
    self.radius = radius;
    self.isAllShow = YES;
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [superVie addSubview:self];
    [superVie bringSubviewToFront:self];
    [self removeSubviews];
//    self.frame = superVie.bounds;
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(superVie);
    }];
    [self show];
}

#pragma mark - Actions
//Layer添加旋转动画
- (void)refreshStateRefreshingAnimation{
    CABasicAnimation *rotationAnimation = (CABasicAnimation *)[self.refreshLayer animationForKey:@"rotationAnimation"];
    // 如果layer上不存在动画，则进行添加动画
    if (!rotationAnimation) [self.refreshLayer addAnimation:self.rotationAnimation forKey:@"rotationAnimation"];
    // 如果存在动画则不继续执行
    if (rotationAnimation && self.refreshLayer.speed == 1) return;
    self.refreshLayer.speed = 1;
    [self.refreshLayer addAnimation:self.rotationAnimation forKey:@"scaleAnimation"];
}

- (void)config
{
    self.message = @"加载中";
    self.loadingColor = [UIColor colorWithHex:0x1CBEBC];
    self.radius = 12;
}
#pragma mark - 显示
- (void)show
{
    [self setupUI];
    
    self.hidden = NO;
    [UIView animateWithDuration:DEFAULT_ANIMATION_TIME animations:^{
        self.alpha = 1;
        self.contentView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {

    }];
}

- (void)dismiss
{
    [UIView animateWithDuration:DEFAULT_ANIMATION_TIME animations:^{
        // 设置layer的动画速度为0则停止动画
        self.refreshLayer.speed = 0.0;
        self.alpha = 0;
        self.contentView.transform = CGAffineTransformMakeScale(0.001, 0.001);
    } completion:^(BOOL finished) {
        self.hidden = YES;
        [self removeFromSuperview];
    }];
}

#pragma mark - 设置UI

- (void)setLayer{
    _refreshLayer = [CALayer layer];
    _refreshLayer.backgroundColor = self.loadingColor.CGColor; //圆环底色
    _refreshLayer.frame = CGRectMake(0, 0, self.radius, self.radius);
    //创建一个圆环
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.radius/2, self.radius/2) radius:self.radius/2-2 startAngle:0 endAngle:M_PI*2 clockwise:YES];
    
    //圆环遮罩
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = self.loadingColor.CGColor;
    shapeLayer.lineWidth = 2;
    shapeLayer.strokeStart = 0;
    shapeLayer.strokeEnd = 0.8;
    shapeLayer.lineCap = @"round";
    shapeLayer.lineDashPhase = 0.8;
    shapeLayer.path = bezierPath.CGPath;
    
    //颜色渐变
    NSMutableArray *colors = [NSMutableArray arrayWithObjects:(id)self.loadingColor.CGColor,(id)[[UIColor whiteColor] colorWithAlphaComponent:0.5].CGColor,(id)[[UIColor clearColor] colorWithAlphaComponent:0.5].CGColor, nil];
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.shadowPath = bezierPath.CGPath;
    gradientLayer.frame = CGRectMake(0, 5, self.radius*5/4, self.radius*5/4);
    gradientLayer.locations = @[@(0.2),@(0.8),@(0.5)];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 0);
    [gradientLayer setColors:[NSArray arrayWithArray:colors]];
    [_refreshLayer addSublayer:gradientLayer]; //设置颜色渐变
    [_refreshLayer setMask:shapeLayer]; //设置圆环遮罩
}

- (void)setupUI
{
    [self setLayer];
    [self refreshStateRefreshingAnimation];
    self.contentView.transform = CGAffineTransformMakeScale(0.001, 0.001);
    self.backgroundColor = self.maskBackgroundColor ? self.maskBackgroundColor :[[UIColor clearColor]colorWithAlphaComponent:0.0];
    self.lab.textColor = self.labColor ? self.labColor : [UIColor colorWithHex:0xAAAAAA];
    self.alpha = 0;
    
    self.lab.text = self.message;
    if (self.message.length > 5) {
        self.lab.text = [[self.message substringToIndex:4] stringByAppendingString:@"..."];
    }
    if (self.isToast) {
        self.contentView.backgroundColor = [[UIColor colorWithHex:0x000000] colorWithAlphaComponent:0.7];
        [self.contentView setCornerRadius:8];
        self.refreshLayer.frame = CGRectMake(18, 18, self.radius, self.radius);
    }

    [self.containerView addSubview:self.contentView];
    [self.containerView addSubview:self.lab];
    [self addSubview:self.containerView];
    [self.contentView.layer addSublayer:self.refreshLayer];
    [self setConstraints];
}
- (void)setConstraints{
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self);
        make.height.mas_equalTo(100);
    }];
    if (self.isToast){
        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.containerView.mas_top);
            make.centerX.equalTo(self.containerView.mas_centerX);
            make.width.mas_equalTo(60);
            make.height.mas_equalTo(60);
        }];
    }else{
        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.containerView.mas_top);
            make.width.mas_equalTo(self.radius);
            make.height.mas_equalTo(self.radius);
        }];
    }
    if (self.isAllShow) {
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.centerX.equalTo(self.containerView);
        }];
        [self.lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView.mas_bottom).offset(4);
            make.centerX.equalTo(self.containerView.mas_centerX);
            make.height.mas_equalTo(17);
        }];
    }else{
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.left.equalTo(self.containerView);
        }];
        [self.lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView.mas_right).offset(5);
            make.centerY.equalTo(self.contentView.mas_centerY);
            make.right.equalTo(self.containerView.mas_right).offset(2);
        }];
    }
}

- (void)removeSubviews
{
    if (self.subviews.count) {
        for (UIView *view in self.subviews) {
            [view removeFromSuperview];
        }
    }
}

#pragma mark - lazy

- (CABasicAnimation *)rotationAnimation{
    if (!_rotationAnimation) {
        _rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        _rotationAnimation.fromValue = [NSNumber numberWithFloat:0];
        _rotationAnimation.toValue = [NSNumber numberWithFloat:6.0*M_PI];
        _rotationAnimation.autoreverses = NO;
        _rotationAnimation.fillMode = kCAFillModeForwards;
        _rotationAnimation.repeatCount = MAXFLOAT;
        _rotationAnimation.beginTime = 0.8; //延时执行，注释掉动画会同时进行
        _rotationAnimation.duration = 3;
    }
    return _rotationAnimation;
}
- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [UIView new];
        _contentView.backgroundColor = [UIColor clearColor];
    }
    return _contentView;
}
- (UILabel *)lab{
    if (!_lab) {
        _lab = [[UILabel alloc] init];
        _lab.textColor = [UIColor colorWithHex:0xAAAAAA];
        _lab.font = [UIFont systemFontOfSize:12.0];
    }
    return _lab;
}

- (UIView *)containerView
{
    if (!_containerView) {
        _containerView = [UIView new];
        _containerView.backgroundColor = [UIColor clearColor];
    }
    return _containerView;
}
@end
